<template>
  <div class="wholeTest4double">
    <div class="contentBox">
      <div class="title">双人关系</div>
      <div class="tipInfo">
        <div class="typeBox">
          <span>测评时间：</span>
          <el-date-picker
            :disabled="type=='edit'"
            v-model="testTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
      </div>
      <el-scrollbar>
        <div class="wholeBox">
          <div v-for="(itemrow,indexk) in testArr" :key="indexk+'aaa'">
            <div class="littleTitle">{{itemrow.title.indexOf('父母') >-1? '' : '与'}}{{itemrow.title}}的关系</div>
            <div class="itemBox" v-for="(item,index) in itemrow.testArrSingle" :key="index">
              <div class="selectBox" v-show="item.type == 'select'">
                <strong v-show="!isSick" style="color:red;margin-right:10px;font-no">*</strong>
                <p>{{item.question}}</p>
                <span v-show="itemrow.title.indexOf('父母') >-1 && item.isFirst">{{ itemrow.title.indexOf('祖') >-1?itemrow.title.replace('母',':') : itemrow.title.replace('母','亲:') }}</span>
                <el-select v-model="item.side" :disabled="type=='edit'" v-show="!item.isStep" filterable placeholder="请选择">
                  <el-option
                    v-show="item.useExtra"
                    v-for="row in item.extra1"
                    :key="row-1"
                    :label="row-1"
                    :value="row-1">
                  </el-option>
                  <el-option
                    v-show="!item.useExtra"
                    v-for="row in wholeCard"
                    :key="row"
                    :label="row"
                    :value="row">
                  </el-option>
                </el-select>
                <span v-show="itemrow.title.indexOf('父母') >-1 && item.isFirst" style="margin-left:10px">{{ itemrow.title.indexOf('祖') >-1?itemrow.title.replace('父','') : itemrow.title.replace('父','')+'亲:' }}</span>
                <span v-if="itemrow.title.indexOf('父母') >-1 && item.isFirst" style="border: 1px solid #ccc;padding: 0 10px;margin-left: 5px;">{{otherSelect(item.side)}}</span>
                <div class="stepsBox" v-show="item.isStep" :style="{cursor:(type=='edit'?'not-allowed':'auto')}">
                  <span v-for="(row,rowIdx) in item.extra1" :key="row-1 + 'ddd'" :style="{pointerEvents:(type=='edit'?'none':'auto')}"
                  @click="clickStep(item,row,rowIdx)" :class="{'active':rowIdx == item.activeStep}">
                    {{ row-1 }}
                    <i class="circle" v-show="item.activeStep!=rowIdx" :class="{'activebgc':rowIdx < item.activeStep}"></i>
                    <el-icon v-show="item.activeStep==rowIdx" class="circleActive"><CircleCheckFilled /></el-icon>
                    <i class="line" :class="{'activebgc':rowIdx < item.activeStep}" v-show="rowIdx!=item.extra1-1"></i>
                  </span>
                </div>
              </div>
              <div class="inputBox" v-show="item.type == 'input'">
                <p>{{item.question}}</p>
                <el-input
                  type="textarea"
                  :rows="item.rows"
                  placeholder="请输入"
                  v-model="item.side">
                </el-input>
              </div>
            </div>
          </div>
          <div class="btn">
            <el-button type="primary" size="large" v-show="type!='edit'" @click="saveFn('next')">下一步</el-button>
            <el-button type="primary" size="large" v-show="type=='edit'" @click="saveFn('finish')">完成</el-button>
          </div>
        </div>
      </el-scrollbar>
      <div class="saveBtn">
        <el-button type="primary" size="large" v-show="type!='edit'" @click="saveFn('save')">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { serverSeckAddList, serverSeckGetDetail, serverSeckUpdateList } from '@/api/home.js'
export default {
  data() {
    return {
      personType: 'adult',
      testTime: new Date(),
      itemname: '',
      testType: [],
      type: 'add',
      recordId: '',
      WAIMS_TOKEN: '',
      testArrSingle: [], // 单独一个item
      wholeCard: [],
      relationship: [],
      testArr: [], // 页面渲染数组内容
      selectType: 1,
      isSick: false,
      pid: '',
      question: '',
      isInitAdd: true,
    }
  },
  computed: {
    otherSelect() {
      return (val) => {
        var tt = ''
        if(val.indexOf('A')>-1) {
          tt = val.replace('A','a').replace('a','B')
        } else {
          tt = val.replace('B','b').replace('b','A')
        }
        return tt
        // val.indexOf('A')>-1 ? val.replace('A','a').replace('a','B') : val.replace('B','b').replace('b','A')
      }
    }
  },
  mounted() {
    this.testArrSingle = JSON.parse(JSON.stringify(this.$store.state.doubleTest))
    this.wholeCard = JSON.parse(JSON.stringify(this.$store.state.wholeDoubleCard))
    this.personType = sessionStorage.getItem('personType')
    this.isSick = sessionStorage.getItem('health') == 1 ? true : false
    if(localStorage.getItem('WAIMS_TOKEN') && localStorage.getItem('WAIMS_TOKEN') !== '') {
      this.WAIMS_TOKEN = localStorage.getItem('WAIMS_TOKEN')
      this.type = this.$route.query.type ? this.$route.query.type : 'add'
      this.recordId = this.$route.query.recordId ? this.$route.query.recordId : ''
      this.testType = this.$route.query.testType ? JSON.parse(this.$route.query.testType) : []
      this.selectType = this.$route.query.selectType ? this.$route.query.selectType : 1
      this.pid = this.$route.query.pid ? this.$route.query.pid : ''
      this.question = this.$route.query.question ? this.$route.query.question : ''
      if(this.type == 'edit') {
        this.getDetailFn()
        this.testTime = this.$route.query.testTime
      } else {
        for(let i in this.testType) {
          if(this.testType[i].label == '双人关系') {
            this.relationship = this.testType[i].checkList
          }
        }
        this.testArr = []
        for(let k in this.relationship) {
          this.testArr.push({
            title: this.relationship[k],
            testArrSingle: JSON.parse(JSON.stringify(this.testArrSingle))
          })
        }
        console.log('add:::', this.testArr)
      }
      
    } else {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
  },
  methods: {
    clickStep(item, row, rowIdx) {
      console.log(row,rowIdx)
      item.activeStep = rowIdx
      item.side = rowIdx
    },
    // 点击编辑跳转进来
    getDetailFn() {
      serverSeckGetDetail({
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        id: this.pid,
        question: this.question
      }).then(res => {
        console.log(res)
        if(res.code == 200) {
          var temp = res.data
          this.testArr = temp.map(item => {
            return {
              title: item.desc,
              testArrSingle: JSON.parse(item.record),
              id: item.id,
              testTime: item.testTime
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    formatDateTime (date) {
      var y = date.getFullYear();
      var M = date.getMonth() + 1;
      M = M < 10 ? ('0' + M) : M;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      var mm = date.getMinutes();
      mm = mm < 10 ? ('0' + mm) : mm;
      var ss = date.getSeconds();
      ss = ss < 10 ? ('0' + ss) : ss;
      return y + '-' + M + '-' + d+' '+h+':'+mm+':'+ss;
    },
    // 批量新增
    addFn(val) {
      let backData = []
      for(var i in this.testArr) {
        backData.push({
          btnType: this.isInitAdd?'add':'edit',
          testedId: sessionStorage.getItem('testedId'), // 被试id
          record: JSON.stringify(this.testArr[i].testArrSingle), // 答题卡内容
          parentId: this.recordId, // 第一次提交不用填，后面提交填第一次返回的id
          type: this.selectType, // 0初筛 1全面
          question: '双人', // 分测验（双人、团体、社会情景）
          relation: this.testArr[i].title, // 关系
          testTime: (this.testTime == null || this.testTime == '') ? this.formatDateTime(new Date()) : this.formatDateTime(this.testTime) // 测试时间 2023-11-11 10:10:10
        })
      }
      serverSeckAddList(this.WAIMS_TOKEN,backData).then(res => {
        if(res.code === 200) {
          if(val == 'save') {
            // 保存
            this.isInitAdd = false
            this.$message.success('保存测评记录成功！')
            this.recordId = res.data
          } else {
            this.$message.success('新增测评记录成功！')
            this.recordId = res.data
            for(let k in this.testType) {
              if(this.testType[k].label == '双人关系') {
                this.testType.splice(k,1)
                break
              }
            }
            if(this.testType.length>0) {
              this.$router.push({
                path: this.testType[0].label === '双人关系'?'/wholeTest4double':(this.testType[0].label === '团体关系'?'/wholeTest4Family':'/wholeTest4Society'),
                query: {
                  type: 'add',
                  testType: JSON.stringify(this.testType),
                  selectType: this.selectType,
                  recordId: this.recordId
                }
              })
            } else {
              this.$router.push({
                path: '/personList',
                query: {
                  type: 'look'
                }
              })
            }
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 批量编辑
    editFn(val) {
      let backData = []
      for(var i in this.testArr) {
        backData.push({
          btnType: 'edit',
          id: this.testArr[i].id,
          record: JSON.stringify(this.testArr[i].testArrSingle), // 答题卡内容
          testTime: this.testArr[i].testTime
        })
      }
      serverSeckUpdateList(this.WAIMS_TOKEN,backData).then(res => {
        if(res.code === 200) {
          this.$message.success(val == 'save'?'保存测评记录成功！':'编辑测评记录成功！')
          this.$router.push({
            path: '/personList',
            query: {
              type: 'look'
            }
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    saveFn(str) {
      // 正常儿童，双人、团体前三题必填，社会关系第二题至少选一个人物，第三题必选
      if (!this.isSick) {
        for(var i in this.testArr) {
          for(var k in this.testArr[i].testArrSingle) {
            if(this.testArr[i].testArrSingle[k].type == 'select' && this.testArr[i].testArrSingle[k].isStep === false && this.testArr[i].testArrSingle[k].side === '') {
              this.$message.info('请正确填写信息！')
              return false
            }
          }
        }
      }
      if(this.type == 'add') {
        this.addFn(str)
      } else {
        this.editFn(str)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.wholeTest4double {
  height: calc(100vh - 200px);
  background: url(../assets/images/tongyong.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 100px 140px;
  .contentBox {
    height: calc(100% - 80px);
    padding: 40px 200px;
    background-color: #ffffff;
    box-shadow: 35px 35px 50px 0px 
      rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    position: relative;
    .title {
      font-size: 30px;
      font-weight: 700;
      color: #2b82e7;
      text-align: center;
      padding-bottom: 10px;
    }
    .tipInfo {
      text-align: center;
    }
    .littleTitle {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 700;
      color: #3ec9eb;
    }
    .wholeBox {
    }
    .itemBox {
      padding-bottom: 10px;
      .selectBox, .inputBox {
        >p {
          display: inline-block;
          margin: 0 20px 10px 0
        }
      }
    }
    .stepsBox {
      margin-left: 10px;
      display: inline-flex;
      width: calc(100% - 200px);
      height: 28px;
      background: #efefef;
      padding: 5px 0;
      span {
        display: inline-block;
        width: 9%;
        font-size: 14px;
        color: #999;
        text-align: center;
        position: relative;
        cursor: pointer;
      }
      i {
        display: inline-block;
      }
      .circle {
        display: inline-block;
        background: #999;
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-left: -3px;
      }
      .circleActive {
        display: inline-block;
        position: absolute;
        bottom: -5px;
        left: 50%;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        margin-left: -7px;
        font-size: 14px;
      }
      .line {
        display: inline-block;
        background: #999;
        position: absolute;
        bottom: 0;
        left: 50%;
        width: calc(100% - 6px);
        height: 1px;
        border-radius: 50%;
        margin-left: 3px;
      }
      .active {
        color: #3ec9eb;
      }
      .activebgc {
        background: #3ec9eb;
      }
    }
    .btn {
      text-align: center;
    }
    .saveBtn {
      position: absolute;
      right: 100px;
      bottom: 20px;
    }
  }
}
</style>
<style lang="scss">
.wholeTest4double {
  .el-select {
    .el-input {
      width: 90px;
    }
  }
  .el-divider--vertical {
    border-left: 0;
  }
  .el-scrollbar {
    height: calc(100% - 90px);
  }
}
</style>